package service

import (
	"context"
	pb "digitalhuman/api/user/v1"
	"digitalhuman/internal/biz"
	"digitalhuman/internal/helper"
	"digitalhuman/models"
	"github.com/go-kratos/kratos/v2/log"
)

type UserService struct {
	pb.UnimplementedUserServer
	uz *biz.UserBiz
}

func NewUserService(uc *biz.UserBiz) *UserService {
	return &UserService{uz: uc}
}

func (s *UserService) UpdateUser(ctx context.Context, req *pb.UpdateUserRequest) (*pb.UpdateUserReply, error) {
	return &pb.UpdateUserReply{}, nil
}

func (s *UserService) DeleteUser(ctx context.Context, req *pb.DeleteUserRequest) (*pb.DeleteUserReply, error) {
	return &pb.DeleteUserReply{}, nil
}

func (s *UserService) Login(ctx context.Context, req *pb.LoginRequest) (*pb.LoginReply, error) {
	// 根据用户名先查询一下
	userModel, err := s.uz.FindByUserName(ctx, req.Username)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	err = helper.ComparePasswords(userModel.PassWord, req.Password)
	if err != nil {
		return nil, err
	}

	// 生产jwt token 返回 time.Duration(models.UserJwtDuration)*time.Second,
	token, err := s.uz.GenerateTokenAndSave(userModel, models.UserJwtSecret)
	if err != nil {
		return nil, err
	}

	return &pb.LoginReply{AccessToken: token, TokenType: "Bearer"}, nil
}

func (s *UserService) GetUserInfo(ctx context.Context, req *pb.GetUserRequest) (*pb.GetUserReply, error) {
	userId := ctx.Value("user_id").(float64)
	user, err := s.uz.FindUserById(ctx, int(userId))
	if err != nil {
		return nil, err
	}

	reply := &pb.GetUserReply{}
	reply.Id = uint32(user.ID)
	reply.Name = user.Name
	reply.Tel = user.Tel
	reply.RoleType = uint32(user.RoleType)
	reply.Avatar = user.Avatar
	reply.Duration = uint32(user.Duration)

	return reply, nil
}

func (s *UserService) GetVerifyCode(ctx context.Context, req *pb.GetVerifyCodeReq) (*pb.GetVerifyCodeResp, error) {
	err := s.uz.VerifyCode(ctx, req)
	if err != nil {
		return nil, err
	}

	return &pb.GetVerifyCodeResp{}, nil
}

func (s *UserService) Register(ctx context.Context, req *pb.RegisterRequest) (*pb.RegisterReply, error) {
	_, err := s.uz.Register(ctx, req)
	if err != nil {
		return nil, err
	}
	return &pb.RegisterReply{Code: 0, Message: "注册成功"}, nil
}

func (s *UserService) GetDouYinShareUrl(ctx context.Context, req *pb.DouYinShareRequest) (*pb.DouYinShareReply, error) {
	ret, err := s.uz.GetDouYinShareUrl(ctx, req)
	if err != nil {
		return nil, err
	}
	if ret == "" {
		return &pb.DouYinShareReply{Code: 1, Message: "生产失败", Url: ret}, nil
	}
	return &pb.DouYinShareReply{Code: 0, Message: "生产成功", Url: ret}, nil
}
